package com.qfedu.utils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 *
 * Tx: transaction  谐音
 * 创建者: QF-SUN
 * 创建时间: 2023/4/6 11:33
 * 描述: 事务工具类
 */
public class TxUtils {
    private static final ThreadLocal<Connection> tl = new ThreadLocal<>();

    /**
     *  获取连接对象
     * @return
     */
    public static Connection getConn(){
        //从线程中获取连接对象
        Connection conn = tl.get();
        //如果拿不到连接对象
        if(conn == null) {
            //从连接池中获取连接对象， 再存储到线程中
            conn = DataSourceUtils.getConnection();
            tl.set(conn);
        }
        return conn;

    }

    public static void begin(){
        try {
            getConn().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void commit(){
        try {
            getConn().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback(){
        try {
            getConn().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(){
        try {
            getConn().setAutoCommit(true);
            getConn().close();
            tl.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
